/* http server and subdomain mux */
package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"
	"code.google.com/p/feedgraph/config"
	"flag"
	"log"
)

func init () {

	log.SetPrefix("httpd")
}

func main () {

	flag.Parse()

	for _, redirect := range config.Local.HTTPConfig.Redirects {

		log.Println(redirect.Pattern, " -> ", redirect.Target)
		http.Handle(redirect.Pattern, http.RedirectHandler(redirect.Target, 302))
	}

	for _, proxy := range config.Local.HTTPConfig.Proxies {

		target, err := url.Parse(proxy.Target)

		if err != nil {
			panic(err)
		}

		log.Println(proxy.Pattern, " -> ", proxy.Target)
		http.Handle(proxy.Pattern, httputil.NewSingleHostReverseProxy(target))
	}

	for _, server := range config.Local.HTTPConfig.FileServers {

		log.Println(server.Pattern, " -> ", server.Path)
		http.Handle(server.Pattern, http.FileServer(http.Dir(server.Path)))
	}

	log.Println("httpd listening...")

	err := http.ListenAndServe(":80", nil)

	if err != nil {
		panic(err)
	}
}
